package com.ruoyi.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.RegisterDetailedOrder;
import com.ruoyi.domain.RegisterSummaryOrder;
import com.ruoyi.mapper.*;
import com.ruoyi.service.LogService;
import com.ruoyi.service.OrderRegisterJzjService;
import com.ruoyi.service.OrderRegisterService;
import com.ruoyi.system.service.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

@Service
@SuppressWarnings("unchecked")
public class OrderRegisterServiceImpl implements OrderRegisterService {

    private static Logger baoShangOrderLog = LoggerFactory.getLogger("baoShang_order");

    // 使用AtomicLong保证线程安全的自增序列号
    private static final AtomicLong sequence = new AtomicLong(0);

    @Autowired
    OrderRegisterMapper orderRegisterMapper;

    @Autowired
    HotelMapper hotelMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderRegisterJzjService orderRegisterJzjService;

    @Autowired
    LogService logService;

    @Autowired
    ISysRoleService sysRoleService;

    @Autowired
    OrderRegisterBankRecMapper orderRegisterBankRecMapper;

    @Autowired
    OrderRegisterWeChatRecMapper orderRegisterWeChatRecMapper;

    @Autowired
    OrderRegisterAlipayRecMapper orderRegisterAlipayRecMapperl;

    @Override
    public int insertOrderRegister(Map map) {
        Map insertRegister = new HashMap();
        // 酒店信息
        String orderId = map.get("orderId").toString();
        insertRegister.put("orderId", orderId);
        Map orderObj = orderMapper.getOrderByOrderId(orderId);
        String handleTime = map.get("handleTime").toString();
        insertRegister.put("handleTime", handleTime);
        LocalDate paymentDate = null;

        String orderCode = orderObj.get("orderCode").toString();
        String eOrderCode = orderObj.get("eOrderCode").toString();
        String hotelId = orderObj.get("hotelId").toString();
        String hotelName = orderObj.get("hotelName").toString();
        String startTime = orderObj.get("startTime").toString();
        String endTime = orderObj.get("endTime").toString();
        String fjsNum = orderObj.get("fjsNum").toString();
        String names = orderObj.get("names").toString();
        if (orderObj.get("bsHotelId") != null) {
            String bsHotelId = orderObj.get("bsHotelId").toString();
            insertRegister.put("bsHotelId", bsHotelId);
        }
        insertRegister.put("orderCode", orderCode);
        insertRegister.put("eOrderCode", eOrderCode);
        insertRegister.put("hotelId", hotelId);
        insertRegister.put("hotelName", hotelName);
        insertRegister.put("startTime", startTime);
        insertRegister.put("endTime", endTime);
        insertRegister.put("fjsNum", fjsNum);
        insertRegister.put("names", names);
        insertRegister.put("platformName", "悦游");

        // 结算方式
        int jsfs = Integer.parseInt(orderObj.get("jsfs").toString());
        // 结单节点
        int jdjd = Integer.parseInt(orderObj.get("jdjd").toString());
        // 支付方式
        int zffs = Integer.parseInt(orderObj.get("zffs").toString());
        insertRegister.put("jsfs", jsfs);
        insertRegister.put("jdjd", jdjd);
        insertRegister.put("zffs", zffs);

        // 计算支付日期
        paymentDate = getOrderPaymentDate(jsfs, jdjd, zffs, handleTime, startTime, endTime);
        if (paymentDate != null) {
            insertRegister.put("paymentDate", paymentDate);
        }
        return orderRegisterMapper.insertOrderRegister(insertRegister);
    }

    @Override
    public Map getReserveRegisterList(Map map) {
        if (map.get("registerDate[0]") != null) {
            map.put("startRegisterDate", map.get("registerDate[0]").toString() + " 00:00:00");
        }
        if (map.get("registerDate[1]") != null) {
            map.put("endRegisterDate", map.get("registerDate[1]").toString() + " 23:59:59");
        }

        if (map.get("startTime[0]") != null) {
            map.put("rzStartTime", map.get("startTime[0]").toString());
        }
        if (map.get("startTime[1]") != null) {
            map.put("rzEndTime", map.get("startTime[1]").toString());
        }

        if (map.get("endTime[0]") != null) {
            map.put("ldStartTime", map.get("endTime[0]").toString());
        }
        if (map.get("endTime[1]") != null) {
            map.put("ldEndTime", map.get("endTime[1]").toString());
        }

        if (map.get("refundDate[0]") != null) {
            map.put("refundStartTime", map.get("refundDate[0]").toString());
        }
        if (map.get("refundDate[1]") != null) {
            map.put("refundEndTime", map.get("refundDate[1]").toString());
        }

        if (map.get("paymentDate[0]") != null) {
            map.put("paymentDateStartTime", map.get("paymentDate[0]").toString());
        }
        if (map.get("paymentDate[1]") != null) {
            map.put("paymentDateEndTime", map.get("paymentDate[1]").toString());
        }

        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        int pageNum = Integer.parseInt(map.get("pageNum").toString());
        pageNum = (pageNum - 1) * pageSize;
        map.remove("pageSize");
        map.remove("pageNum");
        map.put("pageSize1", pageSize);
        map.put("pageNum1", pageNum);

        List<Map> reserveRegisterList = orderRegisterMapper.getReserveRegisterList(map);
        int reserveRegisterListCount = orderRegisterMapper.getReserveRegisterCount(map);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(reserveRegisterList);
        rspData.setTotal(reserveRegisterListCount);

        Map map1 = new HashMap();
        // 数据列表
        map1.put("reserveRegisterList", rspData);

        // 合计列表
        if (map.get("orderCode") != null || map.get("eOrderCode") != null) {
            List<RegisterSummaryOrder> summaryExport = orderRegisterMapper.getSummaryExport(map);
            if (summaryExport.size() > 0) {
                map1.put("summaryInfo", summaryExport.get(0));
            }
        }

        // 昨日待支付条数
        int yesterdayPaymentPendingCount = orderRegisterMapper.getYesterdayPaymentPendingCount();
        map1.put("yesterdayPaymentPendingCount", yesterdayPaymentPendingCount);
        return map1;
    }

    @Override
    public AjaxResult postPaymentValid(JSONArray jsonArray) {
        String baseHotelId = null;
        String basePaymentDate = null;
        BigDecimal cgjOriginal = new BigDecimal(0);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String id = jsonObject.getString("id");
            Map registerInfo = orderRegisterMapper.getReserveRegisterById(id);

            // 先校验空值
            if (registerInfo.get("hotelId") == null) {
                return AjaxResult.error("悦游酒店ID不能为空");
            }
            if (registerInfo.get("paymentDate") == null) {
                return AjaxResult.error("支付日期不能为空");
            }

            // 支付日期
            String paymentDate = registerInfo.get("paymentDate").toString();


            if (i == 0) {
                baseHotelId = registerInfo.get("hotelId").toString();
                basePaymentDate = paymentDate;
            }

            // 支付状态校验
            int zfzt = Integer.parseInt(registerInfo.get("zfzt").toString());
            if (zfzt == 1) {
                return AjaxResult.error("该订单已支付");
            } else if (zfzt == 0) {
                return AjaxResult.error("该订单无需支付");
            }

            // 酒店校验
            if (!baseHotelId.equals(registerInfo.get("hotelId").toString())) {
                return AjaxResult.error("请选择相同酒店");
            }

            // 支付日期相同校验
            if (!basePaymentDate.equals(paymentDate)) {
                return AjaxResult.error("请选择相同的支付日期");
            }

            // 计算采购价
            if (registerInfo.get("platformName").equals("宝尚")) {
                BigDecimal cgj = new BigDecimal(registerInfo.get("cgj").toString());
                cgjOriginal = cgjOriginal.add(cgj);
            } else {
                String orderId = registerInfo.get("orderId").toString();
                Map orderInfo = orderMapper.getOrderByOrderId(orderId);
                BigDecimal cgj = new BigDecimal(orderInfo.get("cgjOriginal").toString());
                cgjOriginal = cgjOriginal.add(cgj);
            }
        }

        Map hotelJzj = orderRegisterJzjService.getHotelJzjByHotelId(baseHotelId);
        BigDecimal hotelDfk = orderRegisterMapper.getHotelDfkPrice(baseHotelId);

        Map map = new HashMap();
        map.put("hotelId", baseHotelId);
        map.put("paymentDate", basePaymentDate.replace("T00:00", ""));
        map.put("cgjOriginal", cgjOriginal);
        map.put("hotelJzj", hotelJzj != null ? hotelJzj : 0);
        map.put("hotelDfk", hotelDfk != null ? hotelDfk : 0);
        return AjaxResult.success(map);
    }

    @Override
    public List<RegisterDetailedOrder> getDetailedExport(Map map) {
        if (map.get("startTime[0]") != null) {
            map.put("rzStartTime", map.get("startTime[0]").toString());
        }
        if (map.get("startTime[1]") != null) {
            map.put("rzEndTime", map.get("startTime[1]").toString());
        }

        if (map.get("endTime[0]") != null) {
            map.put("ldStartTime", map.get("endTime[0]").toString());
        }
        if (map.get("endTime[1]") != null) {
            map.put("ldEndTime", map.get("endTime[1]").toString());
        }

        if (map.get("paymentDate[0]") != null) {
            map.put("paymentDateStartTime", map.get("paymentDate[0]").toString());
        }
        if (map.get("paymentDate[1]") != null) {
            map.put("paymentDateEndTime", map.get("paymentDate[1]").toString());
        }
        return orderRegisterMapper.getDetailedExport(map);
    }

    @Override
    public List<RegisterSummaryOrder> getSummaryExport(Map map) {
        if (map.get("startTime[0]") != null) {
            map.put("rzStartTime", map.get("startTime[0]").toString());
        }
        if (map.get("startTime[1]") != null) {
            map.put("rzEndTime", map.get("startTime[1]").toString());
        }

        if (map.get("endTime[0]") != null) {
            map.put("ldStartTime", map.get("endTime[0]").toString());
        }
        if (map.get("endTime[1]") != null) {
            map.put("ldEndTime", map.get("endTime[1]").toString());
        }

        if (map.get("paymentDate[0]") != null) {
            map.put("paymentDateStartTime", map.get("paymentDate[0]").toString());
        }
        if (map.get("paymentDate[1]") != null) {
            map.put("paymentDateEndTime", map.get("paymentDate[1]").toString());
        }
        return orderRegisterMapper.getSummaryExport(map);
    }

    @Override
    @Transactional
    public AjaxResult postPaymentInfo(Map map) {
        String data = map.get("data").toString();
        String showType = map.get("showType").toString();
        JSONArray paymentInfoList = JSONArray.parseArray(data);
        String batchId = UUID.randomUUID().toString().replaceAll("-", "");
        String zflx = map.get("zflx").toString();
        String paymentDate = map.get("paymentDate").toString();
        String hotelId = map.get("hotelId").toString();
        int ret = 0;

        // 校验
        AjaxResult ajaxResult = validatePaymentDateAfterReconciliation(paymentInfoList, paymentDate);
        if (ajaxResult.isError()) {
            return ajaxResult;
        }
        Long userId = SecurityUtils.getUserId();
        for (int i = 0; i < paymentInfoList.size(); i++) {
            JSONObject jsonObject = paymentInfoList.getJSONObject(i);
            jsonObject.put("userId", userId);
            if (jsonObject.getString("id") == null) {
                String zfqd = jsonObject.getString("zfqd");
                // 插入订单支付信息
                ret += orderRegisterMapper.insertRegisterPayment(jsonObject, batchId);
                if ("4".equals(zfqd)) {
                    // 如果是结转金支付,出结转金
                    orderRegisterJzjService.outJzj(hotelId, jsonObject.getBigDecimal("paymentPrice"));
                }
                // 修改订单支付状态
                jsonObject.put("zfzt", 1);
                jsonObject.put("paymentType", zflx);
                orderRegisterMapper.postEditPaymentInfo(jsonObject);
            } else {
                batchId = jsonObject.getString("batchId");
                // 校验
                ret += orderRegisterMapper.updateRegisterPayment(jsonObject);
            }
        }

        if (ret > 0) {
            if ("edit".equals(showType)) {
                // 删除这个批次的合计重新算
                orderRegisterMapper.deleteRegisterBatchByBatchId(batchId);
            }
            // 汇总各支付渠道共支付了多少钱
            List<Map> zfqdPaymentPriceSumByBatchId = orderRegisterMapper.getZfqdPaymentPriceSumByBatchId(batchId);
            orderRegisterMapper.insertZfqdPaymentPriceSum(batchId, zfqdPaymentPriceSumByBatchId);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public Map getReserveRegisterById(String id) {
        return orderRegisterMapper.getReserveRegisterById(id);
    }

    @Override
    public List<Map> getOrderRegisterPayment(Map map) {
        // 支付信息
        return orderRegisterMapper.getOrderRegisterPayment(map);
    }

    @Override
    public List<Map> getOrderRegisterRefund(Map map) {
        // 返款信息
        return orderRegisterMapper.getOrderRegisterRefund(map);
    }

    @Override
    public BigDecimal getHotelDfkPrice(Map map) {
        String hotelId = map.get("hotelId").toString();
        return orderRegisterMapper.getHotelDfkPrice(hotelId);
    }

    @Override
    public Map getRegisterAndPaymentByBatchId(Map map) {
        String registerId = map.get("registerId").toString();
        String batchId = orderRegisterMapper.getBatchIdByRegisterId(registerId);

        // 获取这个订单产生的登记单的一些信息
        Map registerInfo = orderRegisterMapper.getReserveRegisterById(registerId);
        String hotelId = registerInfo.get("hotelId").toString();

        // 酒店结转金
        Map hotelJzj = orderRegisterJzjService.getHotelJzjByHotelId(hotelId);

        // 酒店待返款
        BigDecimal hotelDfk = getHotelDfkPrice(registerInfo);

        // 获取这个批次的订单
        List<Map> orderList = orderRegisterMapper.getOrderListByBatchId(batchId);

        // 获取这个批次的支付信息
        Map map1 = new HashMap();
        map1.put("batchId", batchId);
        List<Map> orderRegisterPaymentList = orderRegisterMapper.getOrderRegisterPayment(map1);

        Map map2 = new HashMap();
        map2.put("hotelId", hotelId);
        map2.put("registerInfo", registerInfo);
        map2.put("hotelJzj", hotelJzj);
        map2.put("hotelDfk", hotelDfk);
        map2.put("orderList", orderList);
        map2.put("orderRegisterPaymentList", orderRegisterPaymentList);
        return map2;
    }

    @Override
    public AjaxResult importBaoShangOrder(String username, String password, JSONObject body) {

        // 登录认证
        if (username == null || password == null) {
            return AjaxResult.error("请添加用户名及密码");
        }
        if (!"ahyy".equals(username) || !"ahyy@2024".equals(password)) {
            return AjaxResult.error("用户名或密码错误");
        }

        String bsHotelId = body.getString("bsHotelId");
        String handleTime = body.getString("handleTime");
        String orderCode = body.getString("orderCode");
        String eOrderCode = body.getString("eOrderCode");
        String names = body.getString("names");
        String cgj = body.getString("cgj");
        String startTime = body.getString("startTime");
        String endTime = body.getString("endTime");
        String fjsNum = body.getString("fjsNum");

        // 参数校验
        if (bsHotelId == null || handleTime == null || orderCode == null || eOrderCode == null || names == null || cgj == null || startTime == null || fjsNum == null) {
            return AjaxResult.error("缺少必要参数");
        }

        // 防重判断
        int registerCount = orderRegisterMapper.getRegisterCountByOrderCode(orderCode, eOrderCode);
        if (registerCount > 0) {
            return AjaxResult.error("订单已存在");
        }

        String baoShangOrderInfoJsonStr = body.toString();
        baoShangOrderLog.info(baoShangOrderInfoJsonStr);

        body.put("platformName", "宝尚");

        // 根据宝尚酒店Id查询酒店信息
        Map map = new HashMap();
        map.put("bsHotelId", bsHotelId);
        List<Map> hotelList = hotelMapper.getHotelList(map);
        if (hotelList.size() == 1) {
            // 正确检索到酒店信息
            Map hotelInfo = hotelList.get(0);
            int jsfs = Integer.parseInt(hotelInfo.get("jsfs").toString());
            int jdjd = Integer.parseInt(hotelInfo.get("jdjd").toString());
            int zffs = Integer.parseInt(hotelInfo.get("zffs").toString());
            String hotelId = hotelInfo.get("hotelId").toString();
            String hotelName = hotelInfo.get("hotelName").toString();
            LocalDate paymentDate = getOrderPaymentDate(jsfs, jdjd, zffs, handleTime, startTime, endTime);
            body.put("jsfs", jsfs);
            body.put("jdjd", jdjd);
            body.put("zffs", zffs);
            body.put("hotelId", hotelId);
            body.put("hotelName", hotelName);
            body.put("paymentDate", paymentDate);
        }
        orderRegisterMapper.insertOrderRegister(body);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult importBaoShangOrder(JSONObject body) {
        String handleTime = body.getString("handleTime").replace("T", " ").replace(".000Z", "");
        String orderCode = body.getString("orderCode");
        String eOrderCode = body.getString("eOrderCode");
        String names = body.getString("names");
        String cgj = body.getString("cgj");
        String jsj = body.getString("jsj");
        String startTime = body.getString("startTime");
        String endTime = body.getString("endTime");
        String fjsNum = body.getString("fjsNum");
        // 防重判断
        int registerCount = orderRegisterMapper.getRegisterCountByOrderCode(orderCode, eOrderCode);
        if (registerCount > 0) {
            return AjaxResult.error("订单已存在");
        }
        Map map = new HashMap();
        if (body.getString("bsHotelId") != null) {
            map.put("bsHotelId", body.getString("bsHotelId"));
        } else {
            map.put("hotelId", body.getString("hotelId"));
        }

        List<Map> hotelList = hotelMapper.getHotelList(map);
        if (hotelList.size() == 1) {
            // 正确检索到酒店信息
            Map hotelInfo = hotelList.get(0);
            int jsfs = Integer.parseInt(hotelInfo.get("jsfs").toString());
            int jdjd = Integer.parseInt(hotelInfo.get("jdjd").toString());
            int zffs = Integer.parseInt(hotelInfo.get("zffs").toString());
            String hotelId = hotelInfo.get("hotelId").toString();
            String bsHotelId = hotelInfo.get("bsHotelId").toString();
            String hotelName = hotelInfo.get("hotelName").toString();
            LocalDate paymentDate = getOrderPaymentDate(jsfs, jdjd, zffs, handleTime, startTime, endTime);
            body.put("jsfs", jsfs);
            body.put("jdjd", jdjd);
            body.put("zffs", zffs);
            body.put("hotelId", hotelId);
            body.put("bsHotelId", bsHotelId);
            body.put("hotelName", hotelName);
            body.put("paymentDate", paymentDate);
        }
        orderRegisterMapper.insertOrderRegister(body);
        return AjaxResult.success();
    }

    @Override
    public String getBaoShangToken() {
        return orderRegisterMapper.getBaoShangToken();
    }

    @Override
    public int updateBaoShangToken(String token) {
        return orderRegisterMapper.updateBaoShangToken(token);
    }

    @Override
    public AjaxResult postRefundInfo(Map map) {
        String data = map.get("data").toString();
        JSONArray refundInfoList = JSONArray.parseArray(data);
        String hotelId = map.get("hotelId").toString();
        // 校验
        AjaxResult ajaxResult = validateRefundDateAfterReconciliation(refundInfoList);
        if (ajaxResult.isError()) {
            return ajaxResult;
        }

        Long userId = SecurityUtils.getUserId();
        for (int i = 0; i < refundInfoList.size(); i++) {
            JSONObject jsonObject = refundInfoList.getJSONObject(i);
            jsonObject.put("userId", userId);
            if (jsonObject.get("id") == null) {
                orderRegisterMapper.insertRegisterRefund(jsonObject);
                if ("3".equals(jsonObject.getString("fkqd"))) {
                    // 这里如果是结转金退的话,出结转金
                    BigDecimal refundPrice = jsonObject.getBigDecimal("refundPrice");
                    orderRegisterJzjService.inJzj(hotelId, refundPrice);
                }
            } else {
                // 判断isDisabled,为false方可修改
                System.out.println(jsonObject);
                if (jsonObject.getBoolean("isDisabled") == false || jsonObject.getBoolean("isChangeZfqd") == true) {
                    if ("3".equals(jsonObject.getString("fkqd"))) {
                        // 这里如果是结转金退的话,出结转金
                        BigDecimal refundPrice = jsonObject.getBigDecimal("refundPrice");
                        orderRegisterJzjService.inJzj(hotelId, refundPrice);
                    }
                    orderRegisterMapper.updateRegisterRefund(jsonObject);
                }
            }
        }
        // 看一下这个订单的返款情况
        map = checkOrderStatus(map);
        orderRegisterMapper.postEditPaymentInfo(map);
        return AjaxResult.success();
    }

    @Override
    public int postEditPaymentInfo(Map map) {
        if (map.get("registerType") != null) {
            String registerType = map.get("registerType").toString();
            // 如果变更为消退单
            if ("1".equals(registerType)) {
                map = checkOrderStatus(map);
            }
        }
        return orderRegisterMapper.postEditPaymentInfo(map);
    }

    /**
     * 主要针对返款状态查询
     */
    public Map checkOrderStatus(Map map) {
        map.put("refundStatus", 1);
        List<Map> paymentList = orderRegisterMapper.getOrderRegisterPayment(map);
        List<Map> refundList = orderRegisterMapper.getOrderRegisterRefund(map);
        int payCount = paymentList.size();
        int refundCount = refundList.size();

        if (payCount == 0 && refundCount == 0) {
            // 没有支付也没有返款 = 无需支付
            map.put("zfzt", 0);
        } else if (payCount > 0 && refundCount == 0) {
            // 有支付没返款 = 待返款
            map.put("zfzt", 3);
        } else if (payCount > 0 && refundCount > 0) {
            // 有支付有返款 = 已返款
            map.put("zfzt", 4);
        }
        return map;
    }

    // 计算支付时间
    public LocalDate getOrderPaymentDate(int jsfs, int jdjd, int zffs, String handleTime, String startTime, String endTime) {
        // 初始时间
        String initTimeStr;
        switch (jdjd) {
            case 0:
                // 预定后付 = 订单接受日期
                initTimeStr = handleTime;
                break;
            case 1:
                // 入住日付 = 订单入住日期
                initTimeStr = startTime;
                break;
            case 2:
                // 到店后付 = 订单入住日期
                initTimeStr = startTime;
                break;
            case 3:
                // 离店后付 = 订单离店日期
                initTimeStr = endTime;
                break;
            default:
                initTimeStr = null;
        }
        LocalDate paymentDate = null;
        if (initTimeStr != null) {
            LocalDate initTime = LocalDate.parse(initTimeStr.substring(0, 10));
            switch (jsfs) {
                case 0:
                    // 单结,取确认的日期
                    paymentDate = initTime;
                    break;
                case 2:
                    // 日结,取次日
                    paymentDate = DateUtils.getPaymentDate(initTime, "次日");
                    break;
                case 3:
                    // 周结,取下周一
                    paymentDate = DateUtils.getPaymentDate(initTime, "下周一日");
                    break;
                case 7:
                    // 半月结,小于16号的取本月16日,大于等于16号的取次月1日
                    // 本月16日
                    LocalDate byslr = DateUtils.getPaymentDate(initTime, "本月十六日");
                    int i = initTime.compareTo(byslr);
                    if (i < 0) {
                        // 小于16日
                        paymentDate = byslr;
                    } else {
                        // 大于等于16日
                        paymentDate = DateUtils.getPaymentDate(initTime, "下月一日");
                    }
                    break;
                case 4:
                    // 月结,取下月1日
                    paymentDate = DateUtils.getPaymentDate(initTime, "下月一日");
            }
        }
        return paymentDate;
    }

    @Override
    public AjaxResult postAddRegister(JSONObject jsonObject) {
        AjaxResult ajaxResult = importBaoShangOrder(jsonObject);
        if (ajaxResult.isSuccess()) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public int postCopyRegister(JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        insertLog("复制订单 id:" + id);
        return orderRegisterMapper.insertCopyRegister(id);
    }

    @Override
    public AjaxResult postDeleteRegister(JSONObject jsonObject) {
        // 首先验证权限
        boolean isDelete = verifyPermissions();

        if (!isDelete) {
            return AjaxResult.error("无删除权限");
        }

        // 查询是否已经支付了
        String id = jsonObject.getString("id");
        Map registerInfo = orderRegisterMapper.getReserveRegisterById(id);
        String zfzt = registerInfo.get("zfzt").toString();
        if (!"2".equals(zfzt)) {
            return AjaxResult.error("只允许删除待支付订单");
        }
        // 删除
        int i = orderRegisterMapper.deleteRegisterById(id);
        if (i > 0) {
            insertLog("删除订单 orderCode:" + jsonObject.getString("orderCode"));
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult postEmptyRegister(JSONObject jsonObject) {
        // 首先验证权限
        boolean isDelete = verifyPermissions();

        if (!isDelete) {
            return AjaxResult.error("无清空权限");
        }

        String id = jsonObject.getString("id");
        Map registerInfo = orderRegisterMapper.getReserveRegisterById(id);

        if ("2".equals(registerInfo.get("zfzt").toString())) {
            return AjaxResult.error("该订单未支付");
        }

        if ("并单支付".equals(registerInfo.get("paymentType").toString())) {
            return AjaxResult.error("并单支付无法清空");
        }

        List<String> batchIds = orderRegisterMapper.getPaymentBatchIdById(id);
        if (batchIds.size() > 0) {
            orderRegisterMapper.deleteBatchByBatchId(batchIds);
            orderRegisterMapper.deletePaymentInfoById(id);
            orderRegisterMapper.deleteRefundInfoById(id);
        }

        Map map = new HashMap();
        map.put("registerId", id);
        map.put("zfzt", "2");
        map.put("paymentType", "");
        int i = orderRegisterMapper.postEditPaymentInfo(map);
        insertLog("清空订单 id:" + id);
        if (i > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public int postImportRegister(JSONObject jsonObject) {
        System.out.println(jsonObject);
        String orderId = jsonObject.getString("orderId");
        String handleTime = DateUtils.getDate2();
        Map map = new HashMap();
        map.put("orderId", orderId);
        map.put("handleTime", handleTime);
        int i = insertOrderRegister(map);

        // 日志
        Map orderInfo = orderMapper.getOrderByOrderId(orderId);
        String orderCode = orderInfo.get("orderCode").toString();
        logService.insertOrderLog(orderCode, "导入登记表", 2);

        return i;
    }

    /**
     * 删除、清空权限校验(仅公司管理员可以操作)
     *
     * @return
     */
    private boolean verifyPermissions() {
        Long userId = SecurityUtils.getUserId();
        Boolean isDelete = false;
        List<SysRole> sysRoles = sysRoleService.selectRolesByUserId(userId);
        for (SysRole sysRole : sysRoles) {
            // 只有公司管理员可以删除
            Long roleId = sysRole.getRoleId();
            if (roleId == 6) {
                isDelete = true;
            }
        }
        return isDelete;
    }

    /**
     * 插入日志表
     *
     * @param logDescribe
     */
    private void insertLog(String logDescribe) {
        Long userId = SecurityUtils.getUserId();
        orderRegisterMapper.insertRegisterLog(logDescribe, userId);
    }

    /**
     * 根据支付渠道获取最后一次对账时间与支付日期比对，支付日期不能小于或等于对账时间
     *
     * @param jsonArray   支付数据集合
     * @param paymentDate 支付时间
     * @return
     */
    private AjaxResult validatePaymentDateAfterReconciliation(JSONArray jsonArray, String paymentDate) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String paymentDateActual = jsonObject.getString("paymentDateActual");
            String zfqd = jsonObject.getString("zfqd");
            // 首先校验实际支付日期与计算得出的支付日期是否相同
            if (!paymentDateActual.equals(paymentDate)) {
                return AjaxResult.error("实际支付日期与支付日期不同,请修改后提交");
            }

            String type = "";
            String recDate = null;
            if ("0".equals(zfqd)) {
                // 预付款
            } else if ("1".equals(zfqd)) {
                // 银行卡
                recDate = orderRegisterBankRecMapper.getMaxSealDate();
                type = "银行卡";
            } else if ("2".equals(zfqd)) {
                // 微信余额
                recDate = orderRegisterWeChatRecMapper.getMaxSealDate();
                type = "微信余额";
            } else if ("3".equals(zfqd)) {
                // 支付宝余额
                recDate = orderRegisterAlipayRecMapperl.getMaxSealDate();
                type = "支付宝余额";
            } else if ("4".equals(zfqd)) {
                // 结转金
            }

            if (recDate != null) {
                // 实际支付时间和最后一次对账时间对比
                int result = DateUtils.compareTimeSizes(paymentDateActual, recDate);
                if (result < 1) {
                    return AjaxResult.error("实际支付日期必须大于" + type + "最后一次对账日期");
                }
            }
        }
        return AjaxResult.success();
    }

    public AjaxResult validateRefundDateAfterReconciliation(JSONArray jsonArray) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String refundDate = jsonObject.getString("refundDate");
            String fkqd = jsonObject.getString("fkqd");

            String type = "";
            String recDate = null;
            if ("0".equals(fkqd)) {
                // 银行卡
                recDate = orderRegisterBankRecMapper.getMaxSealDate();
                type = "银行卡";
            } else if ("1".equals(fkqd)) {
                // 微信余额
                recDate = orderRegisterWeChatRecMapper.getMaxSealDate();
                type = "微信余额";
            } else if ("2".equals(fkqd)) {
                // 支付宝余额
                recDate = orderRegisterAlipayRecMapperl.getMaxSealDate();
                type = "支付宝余额";
            } else if ("3".equals(fkqd)) {
                // 结转金
            } else if ("5".equals(fkqd)) {
                // 预付款
            }

            if (recDate != null) {
                // 实际支付时间和最后一次对账时间对比
                int result = DateUtils.compareTimeSizes(refundDate + " 00:00:00", recDate);
                if (result < 1) {
                    return AjaxResult.error("返款日期必须大于" + type + "最后一次对账日期");
                }
            }
        }
        return AjaxResult.success();
    }
}